import axios, {
	AxiosError,
	type AxiosInstance,
	type AxiosRequestHeaders,
	type AxiosResponse,
	type InternalAxiosRequestConfig
} from 'axios';

import Swal from 'sweetalert2';
import { Message } from '@arco-design/web-vue';
import qs from 'qs';
import { config } from './config';
import { getAccessToken, getRefreshToken, getTenantId, removeToken, setToken } from '@/utils/auth';
import { getTimestamp, getCurrentDate } from '@/utils/index';
import { useCache } from '@/hooks/useCache';
const { wsCache } = useCache();
import { useI18n } from '@/hooks/useI18n';

const { result_code, base_url, request_timeout } = config;
// 是否显示重新登录
export const isRelogin = { show: false }

// 创建axios实例
const service: AxiosInstance = axios.create({
	baseURL: base_url, // api 的 base_url
	timeout: request_timeout, // 请求超时时间
	withCredentials: false // 禁用 Cookie 等信息
})
	
// request拦截器
service.interceptors.request.use(
	async (config: InternalAxiosRequestConfig) => {
	// 超过token结束时间expiresTime一分钟，就跳登录，反正则刷新token
	// 过期时间
	// const expiresTime: any = getTimestamp('2024-12-04 11:14:00');
	// const expiresTime = getTimestamp(wsCache.get('expiresTime'));
	// 当前时间
	// const currentTime = getTimestamp(getCurrentDate());
	// if (expiresTime) {
	// 	if (currentTime - expiresTime > -10 && currentTime - expiresTime < 60) {
	// 		const res = await refreshToken();
	// 		wsCache.set('expiresTime', res.data?.data?.expiresTime);
	// 		setToken(res.data?.data);
	// 	} else if (currentTime - expiresTime >= 60) {
	// 		handleAuthorized(false);
	// 		return Promise.reject();
	// 	}
	// }
	// 是否需要设置 token
	let isToken = (config!.headers || {}).isToken === false;
	if (getAccessToken() && !isToken) {
		config.headers.Authorization = 'Bearer ' + getAccessToken() // 让每个请求携带自定义token
	}
	config.headers['terminal'] = 20;
	config.headers['tenant-id'] = getTenantId();
	config.headers['version'] = import.meta.env.VITE_APP_VERSION; //版本

	const params = config.params || {};
	const data = config.data || false;
	if (config.method?.toUpperCase() === 'POST' && (config.headers as AxiosRequestHeaders)['Content-Type'] ==='application/x-www-form-urlencoded') {
		config.data = qs.stringify(data);
	}
	// get参数编码
	if (config.method?.toUpperCase() === 'GET' && params) {
		let url = config.url + '?';
		for (const propName of Object.keys(params)) {
			const value = params[propName];
			if (value !== void 0 && value !== null && typeof value !== 'undefined') {
				if (typeof value === 'object') {
					for (const val of Object.keys(value)) {
						const params = propName + '[' + val + ']';
						const subPart = encodeURIComponent(params) + '=';
						url += subPart + encodeURIComponent(value[val]) + '&';
					}
				} else {
					url += `${propName}=${encodeURIComponent(value)}&`;
				}
			}
		}
		// 给 get 请求加上时间戳参数，避免从缓存中拿数据
		// const now = new Date().getTime()
		// params = params.substring(0, url.length - 1) + `?_t=${now}`
		url = url.slice(0, -1);
		config.params = {};
		config.url = url;
	}
		return config;
	},
	(error: AxiosError) => {
		// Do something with request error
		Promise.reject(error);
	}
)
	
// response 拦截器
service.interceptors.response.use(
	async (response: AxiosResponse<any>) => {
		const { data } = response;
		if (!data) {
			// 返回“[HTTP]请求没有返回值”;
			throw new Error()
		}
		// 未设置状态码则默认成功状态
		const code = data.code || result_code
		// 二进制数据则直接返回
		if (['blob', 'arraybuffer'].includes(response.request.responseType)) {
			return response.data;
		}
		if([0, 200].includes(code)){
			return data;
		}else{
			if(code === 401){
				wsCache.clear();
				window.location.href = window.location.href;
			}
			return Promise.reject(Message.error(data.msg));
		}
	},
	(error: AxiosError) => {
		if (error) {
			let { message } = error;
			Message.error(message);
		}
		return Promise.reject(error || '请求出错，请稍候重试');
	}
)

// const refreshToken = async () => {
// 	axios.defaults.headers.common['tenant-id'] = getTenantId();
// 	return await axios.post(base_url + '/auth/refresh-token?refreshToken=' + getRefreshToken());
// }
const handleAuthorized = (isTip:Boolean = true) => {
	const { t } = useI18n()
	if (!isRelogin.show) {
		// 如果已经到重新登录页面则不进行弹窗提示
		if (window.location.href.includes('login?redirect=')) {
			return
		}
		isRelogin.show = true;
		Swal.fire({
			title: '系统提示',
			text: '登录超时,请重新登录!',
			icon: 'question',
			showCancelButton: true,
			confirmButtonText: '确定',
			cancelButtonText: '取消'
		}).then((result) => {
			if (result.isConfirmed) {
				wsCache.clear();
				removeToken();
				isRelogin.show = false;
				// 干掉token后再走一次路由让它过router.beforeEach的校验
				window.location.href = window.location.href;
			}
		})
	}
	if (isTip) {
		return Promise.reject(t('sys.api.timeoutMessage'))
	}
}
export { service }
	